import { defineStore } from 'pinia';
import { closeWebsocket, connectWebsocket } from '@/utils/websocket.js';
import { router } from '@/router/index.js';
import { removeToken } from '@/utils/token.js';
import { useUserStore } from '@/store/modules/user.js';

// 收取到通知后方法
function notifyMessage(data) {
  $notify({ title: data.name, content: data.content });
}

// 收取到公告后方法
function noticeMessage(data) {
  $notice({ title: data.name, content: data.content, meta: data.endDate });
}
// 强制踢出用户方法
async function socketLogout(res) {
  await $EvDialog.warning('警告', res.message || '已退出登录');
  const userStore = useUserStore();
  closeWebsocket();
  removeToken();
  userStore.userInfo = null;
  await router.replace({ path: '/login' });
}
export const useSocketStore = defineStore('socket', {
  state() {
    return {
      appSocket: null,
    };
  },
  actions: {
    initAppSocket() {
      const socketUrl = `ws://${location.host}/api/ws/asset`;
      this.appSocket = connectWebsocket(socketUrl, {}, this.getSocketData, this.socketError);
    },
    getSocketData(res) {
      // 定义收取通知类型枚举 (3001:通知,3002:公告)
      const messageMap = {
        3001: notifyMessage, //通知
        3002: noticeMessage, //公告
      };
      // 定义强制退出类型枚举
      const logoutMap = {
        2004: socketLogout,
        2007: socketLogout,
        2008: socketLogout,
        2009: socketLogout,
      };
      let getData = JSON.parse(res);
      if ([3001, 3002].includes(getData.code)) {
        messageMap[getData.code](getData.data);
      } else if ([2004, 2007, 2008, 2009].includes(getData.code)) {
        logoutMap[getData.code](getData);
      }
    },
    socketError(e) {
      console.log(e);
    },
  },
});
